package com.lhy.admin.common.mvcplus.wrapper.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lhy.admin.common.mvcplus.entity.DbField;
import com.lhy.admin.common.mvcplus.wrapper.AbstractSearchComparator;

/**
 * JSONObjectComparator
 *
 * @author hyluan
 * @date 2023年05月23日 9:13
 */
public abstract class AbstractJSONObjectComparator extends AbstractSearchComparator {
    @Override
    public boolean valid(DbField dbField) {
        return super.valid(dbField) && dbField.getName().contains(".");
    }

    @Override
    public void accept(QueryWrapper queryWrapper, DbField dbField) {
        String[] name = dbField.getName().split("\\.");
        //获取属性字段数据类型
        Class attrFieldClass = getAttrFieldClass(queryWrapper, name);
        String[] vals = splitStr(dbField.getValue());
        queryWrapper.nested(qw -> {
            QueryWrapper qw1 = (QueryWrapper) qw;
            for (int i = 0; i < vals.length; i++) {
                Object value = Convert.convert(attrFieldClass, vals[i]);
                qw1.apply(expressionSql(name[0], name[1]), value);
                if (i < vals.length - 1) {
                    qw1.or();
                }
            }
        });
    }

    public abstract String expressionSql(String colName, String attrName);

    /**
     * getAttrFieldClass 获取json属相字段数据类型类
     *
     * @param queryWrapper queryWrapper
     * @param name name
     * @return {@link Class}
     * @author hyluan
     * @date 2023/5/23 10:10
     */
    public abstract Class getAttrFieldClass(QueryWrapper queryWrapper, String[] name);


}
